<template>
  <yt-page title="责令限期整改">
    <yt-form>
      <yt-cell label="文书编号">
        <yt-input :clearable="false" v-model="form.document_num"></yt-input>
      </yt-cell>
      <yt-cell label="整改期限">
        <yt-cell-time v-model="form.check_date"></yt-cell-time>
      </yt-cell>
      <yt-cell label="审批人">
        <yt-cell-select v-model="form.check_person" :max="1" :list="userList" label="DisplayName" val="id"></yt-cell-select>
      </yt-cell>
      <yt-textarea class="input" border="none" title="补充说明" placeholder="请简单描述一下..." type="row" v-model="form.check_remarks"></yt-textarea>
      <yt-split></yt-split>
      <yt-cell label="整改清单">
        <yt-cell-select :list="records" text="添加" :max="999" v-model="selectList" label="danger_desc"></yt-cell-select>
      </yt-cell>
      <p class="row" v-for="(item, index) in selectList" :key="index">{{ index + 1 }}: {{ item.danger_desc }}</p>
      <yt-btn v-if="form.state === 0" slot="btn" :loading="onSubmit" theme="blue" edge>保存</yt-btn>
      <yt-btn-group v-else slot="btn" :shadow="false" edge>
        <yt-btn theme="white" :loading="onSubmit" :loadingOption="{color: '#46baff'}">保存</yt-btn>
        <yt-btn theme="white" :loading="onPreview" :loadingOption="{color: '#46baff'}">预览文书</yt-btn>
      </yt-btn-group>
    </yt-form>
  </yt-page>
</template>

<script>
import { commonApi } from '@/common/api/commonApi.js'
import { PointerToString, BuildPointer } from '@/common/utils/index.js'
import { bridge } from '@/common/plugin/index.js'

export default {
  data() {
    return {
      form: {
        check_date: ''
      },
      selectList: [],
      userList: [],
      records: []
    }
  },
  async activated() {
    if (!this.$router.$isBack) {
      this.init()
      this.fetchData()
      this.fetchRecord()
    }
  },
  methods: {
    async onPreview(loaded) {
      try {
        let word = await commonApi.runCloud('officeCopy', {
          code: 'D0003',
          data: this.$route.query.id
        })
        let { url } = await commonApi.runCloud('WordToPdf', { word })
        if (!url) {
          this.$Toast('文件转换失败，请尝试重新预览！', 'error')
          loaded()
          return
        }
        bridge.PreviewPdf({ title: '文件标题', url: url })
      } catch (e) {}
      loaded()
    },
    async onSubmit(loaded) {
      try {
        let form = BuildPointer(this.form, {
          check_person: 'aj_organization_personnel'
        })
        if (form.state !== 1) {
          form.state = 1
          await commonApi.save('law_plan', {
            id: this.$route.query.id,
            state: 3
          })
        }
        let objects = this.selectList.map(item =>
          commonApi.createInstance('law_record_danger', {
            id: item.id,
            state: 1
          })
        )
        let p = [
          commonApi.save('law_rectify', form),
          commonApi.saveAll(objects)
        ]
        await Promise.all(p)
        this.$router.$back()
        this.$Toast('保存成功!', 'success')
      } catch (e) {
        this.$Toast('保存失败!', 'error')
      }
      loaded()
    },
    async init() {
      this.rectify = this.$route.query.rectify
      let form = await commonApi.searchById('law_rectify', this.rectify)
      this.form = PointerToString(form, ['check_person'])
      if (this.form.document_num) return
      let { D0003 } = await commonApi.runCloud('lawGetDocumentNum', {
        year: new Date().getFullYear()
      })
      this.form = { ...this.form, document_num: D0003 }
    },
    async fetchData() {
      this.userList = await commonApi.search('aj_organization_personnel', {
        include: ['OrganizationIds'],
        matchesQuery: {
          OrganizationIds: commonApi.createQueryIncludeOptions(
            'sys_organizations',
            {
              equalTo: {
                Name: '安监局执法'
              }
            }
          )
        }
      })
    },
    async fetchRecord() {
      let record = this.$route.query.record
      this.records = await commonApi.search('law_record_danger', {
        equalTo: { record_id: record },
        include: ['score']
      })
      this.selectList = this.records.filter(v => v.state)
    }
  }
}
</script>

<style scoped lang="stylus">
.m-t
  margin-top 30px

.row
  font-size 14px
  line-height 36px
  padding 0 10px
</style>
